# This sample code supports Appium Python client >=2.3.0
# pip install Appium-Python-Client
# Then you can paste this into a file and simply run with Python
import os
from time import sleep
from typing import List

from appium import webdriver
from appium.options.common.base import AppiumOptions
from appium.webdriver.common.appiumby import AppiumBy

# For W3C actions
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.support.wait import WebDriverWait

from alipay import util
from core.common import robot_utils
from alipay.util import create_directory_if_not_exists


##################################################################################
def save_text_to_file(text, filename):
    try:
        # 使用 'w' 模式打开文件，如果文件不存在则创建新文件
        with open(filename, 'w', encoding='utf-8') as file:
            # 将文本写入文件
            file.write(text)
    except Exception as e:
        logger.debug(f"写入文件时发生错误: {e}")
    else:
        logger.debug(f"文本已成功写入文件: {filename}")


def getAllTitle(x):
    try:
        return x.text
    except Exception as ex:
        logger.debug(f"提取title失败:{ex}")
    return 'null'


#  提取当前页面的屏幕截图 文案和源码
def save_screenshot_source_text(driver, title, dstFolder, isScroll=False):
    logger.info(f'---->{dstFolder}')
    try:
        save_text_to_file(driver.page_source, f"{dstFolder}/{title}_source.xml")
        moreDetailContextList = driver.find_elements(by=AppiumBy.CLASS_NAME, value="android.widget.TextView")
        lists = moreDetailContextList
        logger.debug(f"文本列表长度:{len(lists)}   {isScroll}")
        for item in lists:
            logger.info(f'{item}')
        if (len(lists) > 0) & isScroll == True:
            for i in range(1, len(lists)):
                if i == len(lists):
                    return
                now = lists[i]
                pre = lists[i - 1]
                #  依次上滑
                driver.drag_and_drop(now, pre, 2)
                sleep(1)
                save_screenshot_source_text(driver, f"{title}_{i}", dstFolder)
        content = '\r\n'.join(map(lambda x: getAllTitle(x), moreDetailContextList))
        save_text_to_file(content, f"{dstFolder}/{title}_content.txt")
        driver.save_screenshot(f'{dstFolder}/{title}_screenshot.png')
    except Exception as ex:
        logger.error(f"提取失败:{ex}")
        save_text_to_file(f'{ex}', f"{dstFolder}/{title}_error.txt")


def swipe_to_bottom(dst_folder):
    """
    滚动截屏
    :return:
    """
    # dst_folder = "screenshots"
    create_directory_if_not_exists(dst_folder)
    title = "swipe_to_bottom"
    logger.info(f'start swipe_to_bottom')
    num = 0
    while True:
        num = num + 1
        driver.save_screenshot(f'{dst_folder}/{title}_{num}_screenshot.png')
        # 获取滑动前页面元素
        before_swipe = driver.page_source
        robot_utils.swipe_up(driver)
        # 获取滑动后页面元素
        after_swipe = driver.page_source
        # 对比滑动前后的页面元素
        # 若滑动前后页面元素完全相同，则滑动失败，已达页尾
        if before_swipe == after_swipe:
            swip_finished = True
            # 若滑动前后页面元素不同，则滑动成功，继续滑动
        else:
            swip_finished = False
        logger.info(f"swip_finished {swip_finished}")
        if swip_finished:
            break


##################################################################################
if __name__ == '__main__':
    logger = util.init_logger()
    dstFolder = 'products/美亚'
    driver = util.init_driver()
    try:
        ##隐式等待5秒
        driver.implicitly_wait(5)
        create_directory_if_not_exists(dstFolder)

        save_screenshot_source_text(driver, "产品信息", dstFolder)

        logger.debug(f'start 更多详情')
        moreDetailIcon = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,
                                             value="new UiSelector().text(\"更多详情\")")
        logger.debug(f'更多详情{moreDetailIcon}')
        moreDetailIcon.click()
        # save_screenshot_source_text(driver, "保障详情", dstFolder, True)
        ## 等待页面加载完毕
        sleep(3)
        swipe_to_bottom("moreDetail")

        ##返回
        backButton = driver.find_element(by=AppiumBy.ANDROID_UIAUTOMATOR,
                                         value="new UiSelector().resourceId(\"com.alipay.mobile.nebulax.integration:id/frameLayout_backButton\")")
        backButton.click()
        logger.debug(f'返回')

        #######################################################################
        swipe_to_bottom("productDetail")



    except Exception as ex:
        logger.debug(ex)
        logger.debug(f"执行异常:{ex}")
    finally:
        driver.quit()
